package com.ct.musicserver.controller;

import com.ct.musicserver.common.errorcode.ControllerErrorCodeConstants;
import com.ct.musicserver.common.exception.ControllerException;
import com.ct.musicserver.common.pojo.CommonResult;
import com.ct.musicserver.controller.result.FindMusicResult;
import com.ct.musicserver.service.LoveMusicService;
import com.ct.musicserver.service.dto.FindMusicDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class LoveMusicController {

    @Autowired
    private LoveMusicService loveMusicService;

    @RequestMapping("/lovemusic/likeMusic")
    public CommonResult<Boolean> likeMusic(@RequestParam Long id) {
        log.info("likeMusic id={}", id);
        loveMusicService.likeMusic(id);
        return CommonResult.success(Boolean.TRUE, "点赞⾳乐成功");
    }

    @RequestMapping("/lovemusic/findlovemusic")
    public CommonResult<List<FindMusicResult>> findLoveMusic(String musicName) {
        log.info("findLoveMusic musicName={}", musicName);
        List<FindMusicDTO> findMusicDTOList = loveMusicService.findLoveMusic(musicName);
        return CommonResult.success(convertToFindMusicResultList(findMusicDTOList), "查询到了所有的收藏的⾳乐");
    }

    @RequestMapping("/lovemusic/deletelovemusic")
    public CommonResult<Boolean> deletelovemusic(Long id) {
        log.info("deletelovemusic id={}", id);
        loveMusicService.deletelovemusic(id);
        return CommonResult.success(Boolean.TRUE, "取消收藏成功!");
    }

    private List<FindMusicResult> convertToFindMusicResultList(List<FindMusicDTO> findMusicDTOList) {
        if (null == findMusicDTOList) {
            throw new ControllerException(ControllerErrorCodeConstants.NOT_FIND_MUSIC);
        }
        List<FindMusicResult> findMusicResultList = findMusicDTOList.stream()
                .map(findMusicDTO -> {
                    FindMusicResult findMusicResult = new FindMusicResult();
                    findMusicResult.setId(findMusicDTO.getId());
                    findMusicResult.setSinger(findMusicDTO.getSinger());
                    findMusicResult.setTime(findMusicDTO.getTime());
                    findMusicResult.setTitle(findMusicDTO.getTitle());
                    findMusicResult.setUrl(findMusicDTO.getUrl());
                    findMusicResult.setUserid(findMusicDTO.getUserid());
                    return findMusicResult;
                }).collect(Collectors.toList());
        return findMusicResultList;
    }
}
